package com.summer.handler;

import com.sunmmer.service.RpcRequest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

//自定义事件处理器
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    //1、定义成员变量
    private ChannelHandlerContext context;
    private String result; //记录服务器返回到数据
    private String param;  //记录将要返回给服务器的数据
    private RpcRequest rpcRequest;

    //2、实现channelActive 当我们读到服务器数据 该方法自动执行
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        this.context = ctx;
    }

    //3、实现channelRead 当我们读到服务器数据 该方法自动执行
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //将读到到服务器到数据msg 设置为成员变量到值
        result = msg.toString();
        notify();
    }

    //4、将客户端到数据写到服务器
    public synchronized Object call() throws InterruptedException {
       // context.writeAndFlush(param);
        context.writeAndFlush(rpcRequest);
        wait();
        return result;
    }

    public void setParam(String param){
        this.param = param;
    }

    public void setRpcRequest(RpcRequest rpcRequest){
        this.rpcRequest = rpcRequest;
    }

}
